package top.saiyin.list;

import java.util.Arrays;

/**
 * @Program: leetcode
 * @Description: 移除元素
 * @Author: sy
 * @Create: 2020-08-26
 **/
public class RemoveElement {

    public static void main(String[] args) {
        int[] nums = {0, 1, 2, 2, 3, 0, 4, 2};
        int[] nums2 = {0, 0, 1, 1, 1, 2, 2, 3, 3, 4};
        int val = 2;
        // 移除元素
        System.out.println(removeElement(nums, val));
        System.out.println(Arrays.toString(nums));

        // 删除重复元素
        System.out.println(removeDuplicates(nums2));
        System.out.println(Arrays.toString(nums2));

    }

    public static int removeElement(int[] nums, int val) {
        int i = 0;
        for (int j = 0; j < nums.length; j++) {
            if (nums[j] != val) {
                nums[i] = nums[j];
                i++;
            }
        }
        return i;
    }

    public static int removeDuplicates(int[] nums) {
        if (nums.length == 0) {
            return 0;
        }
        int i = 0;
        for (int j = 1; j < nums.length; j++) {
            if (nums[j] != nums[i]) {
                i++;
                nums[i] = nums[j];
            }
        }
        return i + 1;
    }
}
